from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                                    QTabWidget, QPushButton, QLabel, QTableWidget,
                                    QCheckBox, QFileDialog, QTableWidgetItem, QHeaderView,
                                    QMessageBox, QFrame, QMenuBar, QMenu, QAction, QToolBar,
                                    QStatusBar, QApplication, QProgressDialog, QLineEdit)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon
import os
import sys
import glob
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple
from ..utils.logger import logger

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 基本变量初始化
        self.recording = False
        self.recording_paused = False
        self.recording_time = None
        self.timer = None
        self.manual_publish_manager = None
        self.tray_icon = None
        
        # 初始化基本UI
        self.init_basic_ui()
        
        # 使用定时器延迟加载其他组件
        QTimer.singleShot(0, self.init_delayed_components)
        
        logger.info("主窗口基本初始化完成")

    def init_basic_ui(self):
        """初始化基本界面"""
        # 设置窗口基本属性
        self.setWindowTitle('EasyShare - 视频发布助手')
        self.setGeometry(100, 100, 1200, 800)

        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建选项卡
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget)
        
        # 创建加载提示标签
        self.loading_label = QLabel("正在加载组件...", self)
        self.loading_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(self.loading_label)
        
        # 创建状态栏
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)
        self.statusBar.showMessage("正在加载...")

    def init_delayed_components(self):
        """延迟初始化其他组件"""
        try:
            # 移除加载提示标签
            self.loading_label.hide()
            self.loading_label.deleteLater()
            
            # 分步骤初始化各个组件
            self._init_managers()
            self._init_ui_components()
            self._init_connections()
            self._load_settings()
            
            # 更新状态栏
            self.statusBar.showMessage("就绪", 3000)
            logger.info("组件初始化完成")
            
        except Exception as e:
            logger.error(f"延迟初始化失败: {str(e)}")
            self.statusBar.showMessage("初始化失败", 3000)

    def _init_managers(self):
        """初始化管理器"""
        from datetime import timedelta
        from src.core.manual_publish import ManualPublishManager
        
        self.recording_time = timedelta()
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_recording_time)
        self.manual_publish_manager = ManualPublishManager()
        
        self.statusBar.showMessage("初始化管理器...", 1000)

    def _init_ui_components(self):
        """初始化UI组件"""
        # 初始化选项卡
        self.init_tabs()
        
        # 初始化菜单和工具栏
        self.init_menu()
        self.init_toolbar()
        
        # 初始化系统托盘
        self.init_tray()
        
        # 初始化录制按钮
        self.recordVideoBtn = QPushButton("开始录制")
        self.pauseVideoBtn = QPushButton("暂停录制")
        self.pauseVideoBtn.setEnabled(False)
        self.stopVideoBtn = QPushButton("停止录制")
        self.stopVideoBtn.setEnabled(False)
        
        # 将录制按钮添加到发布标签页的头部
        publish_tab = self.tab_widget.widget(0)
        publish_layout = publish_tab.layout()
        header_frame = QFrame()
        header_layout = QHBoxLayout(header_frame)
        header_layout.addWidget(QLabel("手动生成视频发布"))
        header_layout.addWidget(self.recordVideoBtn)
        header_layout.addWidget(self.pauseVideoBtn)
        header_layout.addWidget(self.stopVideoBtn)
        publish_layout.insertWidget(0, header_frame)
        
        self.statusBar.showMessage("初始化界面组件...", 1000)

    def _init_connections(self):
        """初始化信号连接"""
        # 连接录制相关的信号
        if hasattr(self, 'record_btn'):
            self.record_btn.clicked.connect(self.toggle_recording)
        if hasattr(self, 'pause_btn'):
            self.pause_btn.clicked.connect(self.toggle_pause)
        if hasattr(self, 'stop_btn'):
            self.stop_btn.clicked.connect(self.stop_recording)
        
        # 新增录制按钮的信号连接
        if hasattr(self, 'recordVideoBtn'):
            self.recordVideoBtn.clicked.connect(self.toggle_recording)
        if hasattr(self, 'pauseVideoBtn'):
            self.pauseVideoBtn.clicked.connect(self.toggle_pause)
        if hasattr(self, 'stopVideoBtn'):
            self.stopVideoBtn.clicked.connect(self.stop_recording)
        
        self.statusBar.showMessage("初始化信号连接...", 1000)

    def _load_settings(self):
        """加载设置"""
        try:
            # 加载保存的目录
            self.load_saved_directory()
            
            # 应用主题和其他设置
            self.apply_settings()
            
            self.statusBar.showMessage("加载设置...", 1000)
        except Exception as e:
            logger.error(f"加载设置失败: {str(e)}")
            
    def load_saved_directory(self):
        """加载保存的目录设置"""
        try:
            from ..utils.config import config
            video_dir = config.get('video.directory', 'videos')
            if not os.path.isabs(video_dir):
                video_dir = os.path.join(os.getcwd(), video_dir)
            if hasattr(self, 'folder_edit'):
                self.folder_edit.setText(video_dir)
        except Exception as e:
            logger.error(f"加载目录设置失败: {str(e)}")

    def closeEvent(self, event):
        """窗口关闭事件"""
        try:
            # 保存设置
            self.save_settings()
            
            # 关闭托盘图标
            if self.tray_icon:
                self.tray_icon.hide()
            
            event.accept()
            
        except Exception as e:
            logger.error(f"关闭窗口失败: {str(e)}")
            event.ignore()

    def init_tabs(self):
        """初始化标签页"""
        # 发布标签页
        publish_tab = QWidget()
        publish_layout = QVBoxLayout(publish_tab)
        
        # 文件夹选择区域
        folder_frame = QFrame()
        folder_layout = QHBoxLayout(folder_frame)
        
        self.folder_label = QLabel("视频文件夹：")
        self.folder_edit = QLineEdit()
        self.folder_edit.setReadOnly(True)
        self.folder_btn = QPushButton("选择文件夹")
        self.folder_btn.clicked.connect(self.select_video_folder)
        
        folder_layout.addWidget(self.folder_label)
        folder_layout.addWidget(self.folder_edit)
        folder_layout.addWidget(self.folder_btn)
        
        publish_layout.addWidget(folder_frame)
        
        # 视频列表
        self.video_table = QTableWidget()
        self.video_table.setColumnCount(4)
        self.video_table.setHorizontalHeaderLabels(["视频文件", "时长", "大小", "状态"])
        self.video_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        
        publish_layout.addWidget(self.video_table)
        
        # 设置标签页
        settings_tab = QWidget()
        settings_layout = QVBoxLayout(settings_tab)
        
        # 基本设置
        self.auto_publish_cb = QCheckBox("启用自动发布")
        settings_layout.addWidget(self.auto_publish_cb)
        settings_layout.addStretch()
        
        # 添加标签页
        self.tab_widget.addTab(publish_tab, "发布")
        self.tab_widget.addTab(settings_tab, "设置")

    def init_menu(self):
        """初始化菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu('文件')
        
        # 设置菜单项
        settings_action = QAction('设置', self)
        settings_action.setStatusTip('打开设置对话框')
        settings_action.triggered.connect(self.show_settings)
        file_menu.addAction(settings_action)
        
        # 退出菜单项
        exit_action = QAction('退出', self)
        exit_action.setStatusTip('退出应用程序')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 编辑菜单
        edit_menu = menubar.addMenu('编辑')
        
        # 清空列表菜单项
        clear_action = QAction('清空列表', self)
        clear_action.setStatusTip('清空视频列表')
        clear_action.triggered.connect(self.clear_video_list)
        edit_menu.addAction(clear_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu('帮助')
        
        # 关于菜单项
        about_action = QAction('关于', self)
        about_action.setStatusTip('显示关于信息')
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)

    def show_settings(self):
        """显示设置对话框"""
        from .settings_dialog import SettingsDialog
        dialog = SettingsDialog(self)
        dialog.exec_()

    def clear_video_list(self):
        """清空视频列表"""
        if hasattr(self, 'video_table'):
            self.video_table.setRowCount(0)

    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self,
            '关于 EasyShare',
            'EasyShare - 视频发布助手\n\n'
            '一个简单易用的视频录制和发布工具\n'
            '版本：1.0.0\n'
            '作者：EasyShare Team')

    def save_recording(self):
        """保存录制文件"""
        try:
            # TODO: 实现保存录制文件的逻辑
            pass
        except Exception as e:
            logger.error(f"保存录制文件失败: {str(e)}")

    def save_settings(self):
        """保存设置"""
        try:
            from ..utils.config import config
            
            # 保存窗口位置和大小
            config.set('window.geometry', self.saveGeometry().toHex().data().decode())
            config.set('window.state', self.saveState().toHex().data().decode())
            
            # 保存当前标签页
            if hasattr(self, 'tab_widget'):
                config.set('ui.current_tab', self.tab_widget.currentIndex())
            
            # 保存视频列表状态
            if hasattr(self, 'video_table'):
                header_state = self.video_table.horizontalHeader().saveState().toHex().data().decode()
                config.set('ui.video_table_header', header_state)
            
            # 保存自动发布设置
            if hasattr(self, 'auto_publish_cb'):
                config.set('publish.auto_publish', self.auto_publish_cb.isChecked())
        
            # 保存视频目录
            if hasattr(self, 'folder_edit'):
                config.set('video.directory', self.folder_edit.text())
        
            config.save_config()
            logger.info("设置已保存")
            
        except Exception as e:
            logger.error(f"保存设置失败: {str(e)}")

    def init_tray(self):
        """初始化系统托盘"""
        from .tray_icon import SystemTrayIcon
        self.tray_icon = SystemTrayIcon(self)
        self.tray_icon.show()
        logger.info("系统托盘初始化完成")

    def init_toolbar(self):
        """初始化工具栏"""
        # 创建工具栏
        toolbar = QToolBar()
        toolbar.setObjectName("mainToolBar")
        self.addToolBar(toolbar)
        
        # 录制按钮
        record_action = QAction(QIcon(), "开始录制", self)
        record_action.setStatusTip("开始录制视频")
        record_action.triggered.connect(self.toggle_recording)
        toolbar.addAction(record_action)
        
        # 暂停按钮
        pause_action = QAction(QIcon(), "暂停", self)
        pause_action.setStatusTip("暂停录制")
        pause_action.setEnabled(False)
        pause_action.triggered.connect(self.toggle_pause)
        toolbar.addAction(pause_action)
        
        # 停止按钮
        stop_action = QAction(QIcon(), "停止", self)
        stop_action.setStatusTip("停止录制")
        stop_action.setEnabled(False)
        stop_action.triggered.connect(self.stop_recording)
        toolbar.addAction(stop_action)
        
        # 保存工具栏按钮引用
        self.record_action = record_action
        self.pause_action = pause_action
        self.stop_action = stop_action

    def select_video_folder(self):
        """选择视频文件夹"""
        directory = QFileDialog.getExistingDirectory(
            self,
            "选择视频文件夹",
            self.folder_edit.text() or os.path.expanduser("~"),
            QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks
        )
        if directory:
            self.folder_edit.setText(directory)
            self.scan_video_files(directory)
    
    def scan_video_files(self, directory):
        """扫描视频文件夹中的视频文件"""
        try:
            # 清空当前列表
            self.video_table.setRowCount(0)
            
            # 支持的视频格式
            video_extensions = [".mp4", ".avi", ".mov", ".wmv"]
            
            # 扫描文件夹
            for root, _, files in os.walk(directory):
                for file in files:
                    if any(file.lower().endswith(ext) for ext in video_extensions):
                        file_path = os.path.join(root, file)
                        file_info = os.stat(file_path)
                        
                        # 添加到表格
                        row = self.video_table.rowCount()
                        self.video_table.insertRow(row)
                        
                        # 文件名
                        self.video_table.setItem(row, 0, QTableWidgetItem(file))
                        
                        # 时长（待实现）
                        self.video_table.setItem(row, 1, QTableWidgetItem("--"))
                        
                        # 文件大小
                        size_mb = file_info.st_size / (1024 * 1024)
                        self.video_table.setItem(row, 2, QTableWidgetItem(f"{size_mb:.1f} MB"))
                        
                        # 状态
                        self.video_table.setItem(row, 3, QTableWidgetItem("待发布"))
            
            self.statusBar.showMessage(f"找到 {self.video_table.rowCount()} 个视频文件", 3000)
            
        except Exception as e:
            logger.error(f"扫描视频文件失败: {str(e)}")
            self.statusBar.showMessage("扫描视频文件失败", 3000)

    def update_recording_time(self):
        """更新录制时间显示"""
        try:
            if not self.recording:
                return
                
            self.recording_time += timedelta(seconds=1)
            time_str = str(self.recording_time).split('.')[0]  # 去掉毫秒
            
            # 更新界面显示
            if hasattr(self, 'time_label'):
                self.time_label.setText(time_str)
            
            # 更新状态栏
            if hasattr(self, 'status_time_label'):
                self.status_time_label.setText(f"录制时间: {time_str}")
                
            # 更新托盘提示
            if self.tray_icon:
                self.tray_icon.setToolTip(f"EasyShare - 正在录制 ({time_str})")
                
        except Exception as e:
            logger.error(f"更新录制时间失败: {str(e)}")

    def toggle_recording(self):
        """切换录制状态"""
        try:
            if not self.recording:
                # 开始录制
                self.recording = True
                self.recording_paused = False
                self.recording_time = timedelta()
                self.timer.start(1000)  # 每秒更新一次
                
                # 更新UI状态
                self.record_btn.setText("停止录制")
                self.pause_btn.setEnabled(True)
                self.stop_btn.setEnabled(True)
                if hasattr(self, 'record_action'):
                    self.record_action.setText("停止录制")
                    self.pause_action.setEnabled(True)
                    self.stop_action.setEnabled(True)
                
                self.statusBar.showMessage("正在录制...")
                logger.info("开始录制")
                
            else:
                # 停止录制
                self.stop_recording()
                
        except Exception as e:
            logger.error(f"切换录制状态失败: {str(e)}")
            self.statusBar.showMessage("录制操作失败", 3000)

    def toggle_pause(self):
        """切换暂停状态"""
        try:
            if not self.recording:
                return
                
            self.recording_paused = not self.recording_paused
            if self.recording_paused:
                self.timer.stop()
                self.pause_btn.setText("继续")
                if hasattr(self, 'pause_action'):
                    self.pause_action.setText("继续")
                self.statusBar.showMessage("录制已暂停")
                logger.info("录制已暂停")
            else:
                self.timer.start(1000)
                self.pause_btn.setText("暂停")
                if hasattr(self, 'pause_action'):
                    self.pause_action.setText("暂停")
                self.statusBar.showMessage("录制继续...")
                logger.info("录制继续")
                
        except Exception as e:
            logger.error(f"切换暂停状态失败: {str(e)}")
            self.statusBar.showMessage("暂停操作失败", 3000)

    def stop_recording(self):
        """停止录制"""
        try:
            if not self.recording:
                return
                
            self.recording = False
            self.recording_paused = False
            self.timer.stop()
            
            # 更新UI状态
            self.record_btn.setText("开始录制")
            self.pause_btn.setEnabled(False)
            self.stop_btn.setEnabled(False)
            if hasattr(self, 'record_action'):
                self.record_action.setText("开始录制")
                self.pause_action.setEnabled(False)
                self.stop_action.setEnabled(False)
            
            self.statusBar.showMessage("录制已停止")
            logger.info("录制已停止")
            
        except Exception as e:
            logger.error(f"停止录制失败: {str(e)}")
            self.statusBar.showMessage("停止录制失败", 3000)
